package com.shiyipicture.shiyipicturebackend.aop;

import com.shiyipicture.shiyipicturebackend.annotation.AuthCheck;
import com.shiyipicture.shiyipicturebackend.enums.UserRoleEnum;
import com.shiyipicture.shiyipicturebackend.exception.BusinessException;
import com.shiyipicture.shiyipicturebackend.exception.ErrorCode;
import com.shiyipicture.shiyipicturebackend.model.entity.User;
import com.shiyipicture.shiyipicturebackend.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.condition.RequestConditionHolder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.locks.ReentrantLock;

@Aspect
@Component
public class AuthInterceptor {

  @Resource
  private UserService userService;

  /**
   * 执行拦截
   * @param joinPoint
   * @param authCheck
   * @return
   */
  @Around("@annotation(authCheck)")
  public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
    String role = authCheck.mustRole();
    RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
    HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
    //获取当前登录用户
    User loginUser = userService.getLoginUser(request);
    UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(role);

    //不需要权限放行
    if (mustRoleEnum == null) {
      return joinPoint.proceed();
    }

    //必须有权限才会通过
    String userRole = loginUser.getUserRole();
    UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(userRole);
    if (userRoleEnum == null) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
    }
    if (UserRoleEnum.ADMIN.equals(mustRoleEnum) && !UserRoleEnum.ADMIN.equals(userRoleEnum)) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
    }
    //放行
   return joinPoint.proceed();
  }
}
